from email.message import EmailMessage
import smtplib  # 负责发送邮件
# from email.mime.text import MIMEText  # 构造文本
# from email.mime.image import MIMEImage  # 构造图片
# from email.mime.multipart import MIMEMultipart  # 将多个集合对象集合起来
# from email.header import Header

import datetime

# 输入发件人昵称、收件人昵称、主题，正文，附件地址,附件名称生成一封邮件
def format_email_message(sender_name, receiver_name, email_Subject, email_text):
    message = EmailMessage()
    message['From'] = sender_name
    message['To'] = receiver_name
    message['Subject'] = email_Subject
    message.set_content(email_text)
 

    return message.as_string()
def send_email(sender, mail_license, receiver, msg):
    server = smtplib.SMTP_SSL(host="smtp.163.com", port=465)
    server.ehlo()
    # 账号
    server.login(sender, mail_license)

    server.sendmail(from_addr=sender, to_addrs=receiver, msg=msg)
    # print("邮件发送成功 " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    
    server.quit()
    
    
if __name__ == '__main__':
    sender = "16605567611@163.com"
    sender_name = "Mr.Bi<16605567611@163.com>"
    # 邮箱授权码,注意这里不是邮箱密码！！
    mail_license = "RBgU8Q63dAyCqfn4"
    receiver_name = "16605567611<16605567611@163.com>"
    
    # 邮件主题
    subject_content = """Python自动邮件发送"""
    # 邮件正文
    body_content = """你好，这是一个自动发送邮件代码！"""
    

    message = format_email_message(
        sender_name=sender_name,
        receiver_name=receiver_name,
        email_Subject=subject_content,
        email_text=body_content,
        )
    
    send_email(sender=sender,
               mail_license=mail_license,
               receiver=receiver_name,
               msg=message)
